<template>
  <NavBar /> <!-- 顶部导航栏 -->
  <div class="user-center-layout">
    <!-- 左侧导航栏 -->
    <aside class="sidebar">
      <div class="user-summary">
        <img :src="user.avatar" alt="头像" class="sidebar-avatar" />
        <div class="sidebar-nickname">{{ user.nickname || user.username }}</div>
        <button class="logout-btn" @click="logout">退出登录</button>
      </div>
      <div v-for="tab in tabs" :key="tab.key"
           :class="['menu-item', { active: activeTab === tab.key }]"
           @click="activeTab = tab.key">
        {{ tab.label }}
      </div>
    </aside>

    <!-- 右侧内容 -->
    <section class="main-content">
      <ProfileCard
        v-if="activeTab === 'profile'"
        :user="user"
        :userPosts="userPosts"
        :isEditing="isEditing"
        :editedUser="editedUser"
        :activeTab="activeTab"
        @edit="editProfile"
        @save="saveProfile"
        @avatar-change="onAvatarChange"
        @change-tab="activeTab = $event"
        @update-field="updateField"
      />
      <ChangePasswordCard
        v-else-if="activeTab === 'changePassword'"
        :userId="user.userId"
        @change-tab="activeTab = $event"
      />
      <MessageManager v-else-if="activeTab === 'messages'" :messages="messages" />
      <PointLog v-else-if="activeTab === 'points'" :records="pointRecords" />
      <FavoriteList v-else-if="activeTab === 'favorites'" :posts="favoritePosts" />
    </section>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ProfileCard from '@/components/ProfileCard.vue'
import ChangePasswordCard from '@/components/ChangePasswordCard.vue'
import MessageManager from '@/components/MessageManager.vue'
import PointLog from '@/components/PointLog.vue'
import FavoriteList from '@/components/FavoriteList.vue'
import { useUserStore } from '@/stores/user'
import { usePostStore } from '@/stores/post'
import NavBar from '@/components/NavBar.vue'
import axios from 'axios'

const tabs = [
  { key: 'profile', label: '个人资料' },
  { key: 'changePassword', label: '修改密码' },
  { key: 'messages', label: '消息管理' },
  { key: 'points', label: '积分记录' },
  { key: 'favorites', label: '我的收藏' }
]

const activeTab = ref('profile')
const router = useRouter()
const userStore = useUserStore()
const postStore = usePostStore()
const user = computed(() => userStore.currentUser)
const userPosts = computed(() => postStore.userPosts(user.value?.username || ''))

const isEditing = ref(false)
const editedUser = ref({})

const messages = ref([])
const pointRecords = ref([])
const favoritePosts = ref([])

onMounted(() => {
  if (user.value) {
    editedUser.value = {
      userId: user.value.userId,
      nickname: user.value.nickname || '',
      userEmail: user.value.userEmail || '',
      userPhone: user.value.userPhone || '',
      avatar: user.value.avatar || ''
    }
  }
})

const editProfile = () => {
  isEditing.value = true
  editedUser.value = { ...user.value }
}

const saveProfile = async () => {
  try {
    const res = await axios.post('/api/updateProfile', editedUser.value)
    userStore.updateUser(res.data)
    isEditing.value = false
    alert('保存成功')
  } catch (err) {
    alert('保存失败')
  }
}

const onAvatarChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  const formData = new FormData()
  formData.append('avatar', file)
  formData.append('userId', user.value.userId)

  try {
    const res = await axios.post('/api/uploadAvatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    editedUser.value.avatar = res.data.avatar
    userStore.updateUser({ ...user.value, avatar: res.data.avatar })
    alert('头像上传成功')
  } catch (error) {
    alert('头像上传失败')
  }
}

const updateField = ({ key, value }) => {
  editedUser.value[key] = value
}

const logout = () => {
  userStore.logout()
  router.push('/home')
}

</script>

<style scoped>
.user-center-layout {
  display: flex;
}
.sidebar {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #ddd;
  padding-top: 20px;
}
.user-summary {
  text-align: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
.sidebar-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 5px;
}
.sidebar-nickname {
  font-weight: bold;
  margin-bottom: 10px;
}
.to-dashboard {
  padding: 5px 10px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin-bottom: 10px;
}
.to-dashboard:hover {
  background-color: #40a9ff;
}
.menu-item {
  padding: 15px 20px;
  cursor: pointer;
  border-left: 4px solid transparent;
}
.menu-item.active {
  background-color: #e6f7ff;
  border-left-color: #1890ff;
  color: #1890ff;
}
.main-content {
  flex: 1;
  padding: 30px;
  background-color: white;
}
.logout-btn {
  padding: 5px 10px;
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}
.logout-btn:hover {
  background-color: #dd6161;
}

</style>
